package section

import (
	"context"
	"strconv"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	"github.com/volatiletech/null/v8"
	"github.com/zeromicro/go-zero/core/logx"
)

type CreateSectionLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateSectionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateSectionLogic {
	return &CreateSectionLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateSectionLogic) CreateSection(in *backend.SectionInfo) (*backend.BaseIDResp, error) {
	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if in.Type == nil || *in.Type == 0 {
		return nil, errorx.NewInvalidArgumentError("section.typeRequired")
	}

	now := time.Now()
	section := &model.Section{
		Type:      uint8(*in.Type),
		CreatedAt: now,
		UpdatedAt: now,
	}

	if in.Title != nil {
		section.Title = strings.TrimSpace(*in.Title)
	}
	if in.Subtitle != nil {
		section.Subtitle = strings.TrimSpace(*in.Subtitle)
	}
	if in.PicId != nil && *in.PicId > 0 {
		section.PicID = *in.PicId
	}
	if in.PicUrl != nil {
		section.PicURL = strings.TrimSpace(*in.PicUrl)
	}
	if in.Status != nil {
		section.Status = uint8(*in.Status)
	} else {
		section.Status = uint8(globalkey.StatusEnabled)
	}
	if in.Sort != nil {
		section.Sort = uint16(*in.Sort)
	} else {
		section.Sort = uint16(globalkey.SystemDefaultSort)
	}
	if in.StartedAt != nil {
		if localTime, err := modelx.ParseLocalTime(*in.StartedAt); err == nil {
			section.StartedAt = null.TimeFrom(localTime)
		}
	}
	if in.EndedAt != nil {
		if localTime, err := modelx.ParseLocalTime(*in.EndedAt); err == nil {
			section.EndedAt = null.TimeFrom(localTime.Add(time.Minute * -1))
		}
	}

	rel := &model.SectionRel{}
	if len(in.NewMedia) > 0 {
		var thumbnailOrder uint
		var thumbnailId uint64
		var thumbnailUrl string
		for idx, v := range in.NewMedia {
			var url string
			if v.Url != nil && len(*v.Url) > 0 {
				url = *v.Url
			}
			if len(url) == 0 && v.Uri != nil && len(*v.Uri) > 0 {
				url = *v.Uri
			}
			if len(url) == 0 {
				continue
			}

			var thumbnail uint8
			if v.Thumbnail != nil && *v.Thumbnail > 0 {
				thumbnail = uint8(*v.Thumbnail)
			}
			var order uint
			if v.Order != nil {
				order = uint(*v.Order)
			} else {
				order = uint(idx) + globalkey.AttachmentOrderOffset
			}
			var altText string
			if v.AltText != nil && len(*v.AltText) > 0 {
				altText = *v.AltText
			}

			var meta []string
			if v.Name != nil && len(*v.Name) > 0 {
				meta = append(meta, "filename:"+*v.Name)
				if len(altText) == 0 {
					altText = *v.Name
				}
			}
			if v.MetaData != nil && len(*v.MetaData) > 0 {
				meta = append(meta, *v.MetaData)
			}
			if v.MimeType != nil && len(*v.MimeType) > 0 {
				meta = append(meta, "mimeType:"+*v.MimeType)
			}
			metaData := strings.Join(meta, ";")

			var mediaId uint64
			if v.Id != nil && len(*v.Id) > 0 {
				if i, err := strconv.ParseInt(*v.Id, 10, 64); err == nil {
					mediaId = uint64(i)
				}
			}

			rel.Media = append(rel.Media, &model.AttachmentRelationship{
				AttachmentID:        mediaId,
				AttachmentThumbnail: thumbnail,
				AttachmentOrder:     order,
				AttachmentImageURL:  url,
				AttachmentImageAlt:  altText,
				AttachmentImageMeta: metaData,
			})

			if thumbnail > 0 && (len(thumbnailUrl) == 0 || thumbnailOrder > order) {
				thumbnailOrder = order
				thumbnailId = mediaId
				thumbnailUrl = url
			}
		}

		if len(section.PicURL) == 0 {
			section.PicID = thumbnailId
			section.PicURL = thumbnailUrl
		}
	}

	err = l.svcCtx.Section.Insert(l.ctx, tx, section, rel)
	if err != nil {
		tx.Rollback()
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	tx.Commit()

	return &backend.BaseIDResp{
		Id:  section.ID,
		Msg: i18n.CreateSuccess,
	}, nil
}
